package com.v512;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class ShowServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
//		String path = request.getSession().getServletContext().getRealPath(getServletInfo());
		// D:/Eclipse_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/updownload/uploads
		String path = "D:\\Eclipse_workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\updownload\\uploads\\";
		File file = new File(path);
		File[] files = file.listFiles();
		List<String> fileNames = new ArrayList();
		for (File f : files) {
			String fileName = f.getName();
			fileNames.add(fileName);
		}
		request.setAttribute("fileNames", fileNames);
		request.getRequestDispatcher("/show.jsp").forward(request, response);
	}

	public void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items = upload.parseRequest(request);
		Iterator<FileItem> it = items.iterator();
		while (it.hasNext()) {
			FileItem item = (FileItem) it.next();
			if (item.getName() != null && !item.getName().equals("")) {

				String fileName = item.getName();
				//通知浏览器，以下载的方式打开
				response.addHeader("Content-Type", "application/octet-stream");
				response.addHeader("Content-Disposition", "attachment;filename="+fileName);
				//针对要下载的文件，创建了输入流
				File file = new File(item.getName());
				item.write(file);
				FileInputStream in = new FileInputStream(file);
				//获取response的输出流
				ServletOutputStream out = response.getOutputStream();
				byte[] buffer = new byte[1024];
				int len = -1;
				while ((len = in.read(buffer)) != -1) {
					out.write(buffer, 0, len);
				}
				in.close();
				out.close();
			}
		}
	}
}
